#include "loginform.h"
#include "ui_loginform.h"

#include <QTextStream>

LoginForm::LoginForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LoginForm)
{
    ui->setupUi(this);

    task_ = NULL;
    request_ = NULL;
}

void LoginForm::on_exitButton_clicked() {
    emit exitApplicationSignal();
}

void LoginForm::on_loginButton_clicked() {
    QString username = ui->usernameLineEdit->text();
    QString password = ui->passwordLineEdit->text();

    ui->loginButton->setEnabled(false);

    request_ = new LoginRequest(username, password);
    task_ = new AsyncTask(request_, this);

    connect(request_, SIGNAL(error(QString)), this, SLOT(error(QString)));
    connect(request_, SIGNAL(responseStrings(QString,QString)), this, SLOT(loginRequestResponses(QString,QString)));

    task_->execute();
}

void LoginForm::error(QString error)
{
    QMessageBox messageBox(QMessageBox::Warning, tr("Error"), error, QMessageBox::Ok, this);

    messageBox.exec();
}

void LoginForm::loginRequestResponses(QString response, QString cookieValue)
{
    qDebug() << "There...";
    if (response != "Success") {
        ui->loginButton->setEnabled(true);
        QMessageBox msgBox(QMessageBox::Warning, tr("Server Error"), response, QMessageBox::Ok, this);
        msgBox.setModal(true);
        msgBox.exec();
    }
    else {
        emit loginSuccessful(cookieValue);
    }
}

LoginForm::~LoginForm()
{
    delete ui;
}
